package com.itheima.hello.TCP通信.群聊端口转发;

import java.io.*;
import java.net.Socket;
import java.time.LocalDateTime;

public class ServerReaderThread extends Thread{
    private Socket socket;
    public ServerReaderThread(Socket socket){
        this.socket=socket;
}

    @Override
    public void run() {
        try (
                InputStream is = socket.getInputStream();
                DataInputStream dis = new DataInputStream(is);
        ) {
            while (true){
                try {
                    String s = dis.readUTF();
                    System.out.println(LocalDateTime.now() + ":");
                    System.out.println(socket.getRemoteSocketAddress() + ":" + s);

                    //把这个消息群发给全部在线客户端包括自己
                    sendMsgToAll(s);
                    System.out.println("----------------------------");
                } catch (Exception e) {
                    System.out.println(LocalDateTime.now() + ":");
                    System.out.println(socket.getRemoteSocketAddress() + "下线了!!");
                    Server1.onLineSocket.remove(socket);
                    System.out.println("----------------------------");
                    dis.close();
                    socket.close();
                    break;
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    private void sendMsgToAll(String s) throws IOException {
        //发送消息给全部在线客户端
        for (Socket socket1 : Server1.onLineSocket) {
            OutputStream os = socket1.getOutputStream();
            DataOutputStream dos = new DataOutputStream(os);
            dos.writeUTF(s);
            dos.flush();//刷新
        }
    }
}
